<template>
  <div class="content-container">
    <h1>模板管理</h1>

    <!--模板列表-->
    <el-card>
      <div slot="header">
        <el-button type="primary" @click="addTemplate">新增</el-button>
      </div>
      <el-table :data="pageData.records" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"> </el-table-column>
        <el-table-column prop="name" label="模板名称" width="100">
        </el-table-column>
        <el-table-column prop="description" label="模板描述"> </el-table-column>
        <el-table-column prop="path" label="模板路径"> </el-table-column>
        <el-table-column prop="remark" label="备注"> </el-table-column>
        <el-table-column prop="createUser" label="创建人"> </el-table-column>
        <el-table-column prop="createDate" label="创建时间"> </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="text" @click="updateTemplate(scope.row)"
              >更新</el-button
            >
            <el-button type="text" @click="configField(scope.row)"
              >配置字段</el-button
            >
            <el-button type="text" @click="getTemplateStructure(scope.row)"
              >预览</el-button
            >
            <el-button type="text" @click="deleteTemplate(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="pageData.total"
          :page-size="pageConditon.size"
          :current-page="pageConditon.current"
        >
        </el-pagination>
      </div>
    </el-card>

    <!--新增/编辑模板弹出框-->
    <el-dialog
      title="新增/编辑"
      :visible.sync="addEditTemplateDialogVisible"
      :before-close="addEditTemplateDialogClose"
    >
      <el-form :model="templateForm">
        <el-form-item label="模板上传" label-width="100px">
          <div class="template-upload-container">
            <el-upload
              ref="templateUploader"
              drag
              action="/api/common/upload"
              :on-success="fileUploadSuccess"
              :on-error="fileUploadError"
              :multiple="false"
              :limit="1"
              :on-exceed="fileUploadExceed"
              :file-list="templateFileList"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="模板名称" label-width="100px">
          <el-input v-model="templateForm.name"></el-input>
        </el-form-item>
        <el-form-item label="模板路径" label-width="100px">
          <el-input v-model="templateForm.path"></el-input>
        </el-form-item>
        <el-form-item label="模板描述" label-width="100px">
          <el-input v-model="templateForm.description"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="templateForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addEditTemplateDialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" @click="saveTemplate">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="previewTemplateName"
      :visible.sync="previewTemplateDialogVisible"
      width="80%"
    >
      <div>说明：{{ previewTemplateDesc }}</div>
      <div style="padding: 10px 0">备注：{{ previewTemplateRemark }}</div>
      <div id="template-table-container"></div>
    </el-dialog>
  </div>
</template>

<script>
import randerTableUtil from "../util/RanderTabelUtil";
export default {
  data() {
    return {
      pageData: {},
      addEditTemplateDialogVisible: false,
      templateFileList: [],
      templateForm: {
        id: 0,
        name: "",
        path: "",
        description: "",
        remark: "",
      },
      pageConditon: {
        current: 1,
        size: 10,
        condition: {},
      },
      previewTemplateDialogVisible: false,
      previewTemplateName: "",
      previewTemplateDesc: "",
      previewTemplateRemark: "",
      currentPreviewTemplateId: 0,
    };
  },
  mounted() {
    this.requestTemplatePage();
  },
  methods: {
    // 新增模板按钮点击事件
    addTemplate() {
      this.addEditTemplateDialogVisible = true;
    },

    // 更新模板按钮点击事件
    updateTemplate(template) {
      console.log("update:template:::", template);
      this.templateForm = {
        id: template.id,
        name: template.name,
        path: template.path,
        description: template.description,
        remark: template.remark,
      };
      let fileName = template.path.substr(template.path.lastIndexOf("\\") + 1);
      this.templateFileList.push({ name: fileName });
      // console.log(template.path.substr(template.path.lastIndexOf("\\") + 1));
      this.addEditTemplateDialogVisible = true;
    },

    // 保存模板
    saveTemplate() {
      this.$axios
        .post("/api/statistics/template/save", this.templateForm)
        .then((res) => {
          console.log("save:template:::", res.data);
          if (res.data.code === 200) {
            this.$message.success(res.data.data);
            this.addEditTemplateDialogVisible = false;
            this.resetTemplateForm();
            this.requestTemplatePage();
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch((err) => console.log(err));
    },

    // 删除模板
    deleteTemplate(templateId) {
      this.$confirm("此操作将永久删除该模板, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .get(`/api/statistics/template/delete?templateId=${templateId}`)
            .then((res) => {
              // console.log("deleteTemplate:::", res);
              if (res.data.code === 200) {
                this.requestTemplatePage();
                this.$message.success(res.data.message);
              }
            })
            .catch((err) => console.log(err));
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 查询列表
    requestTemplatePage() {
      this.$axios
        .post("/api/statistics/template/page", this.pageConditon)
        .then((res) => {
          if (res.data.code === 200) {
            // console.log(res.data.data);
            this.pageData = res.data.data;
          }
        })
        .catch((err) => console.log(err));
    },

    // 重置form表单参数
    resetTemplateForm() {
      // this.$refs.templateUploader.clearFiles();
      this.templateFileList = [];
      this.templateForm = {
        id: 0,
        name: "",
        path: "",
        description: "",
        remark: "",
      };
    },

    // 配置字段按钮点击事件
    configField(template) {
      this.$router.push({
        path: "/template-field",
        query: {
          templateId: template.id,
        },
      });
    },

    // 获取模板结构
    getTemplateStructure(template) {
      this.previewTemplateDialogVisible = true;
      if (this.currentPreviewTemplateId == template.id) {
        return;
      }
      this.currentPreviewTemplateId = template.id;
      this.$axios
        .get(
          `/api/statistics/template/get-template-structure?templateId=${template.id}`
        )
        .then((res) => {
          // console.log(res);
          if (res.data.code === 200) {
            this.previewTemplateName = res.data.data.name;
            this.previewTemplateDesc = res.data.data.description;
            this.previewTemplateRemark = res.data.data.remark;
            this.$nextTick(() => {
              let tableTemp = randerTableUtil.renderTemplateTable(
                res.data.data.tableStructure,
                "template-table-container"
              );
            });
          }
        })
        .catch((err) => console.log(err));
    },

    addEditTemplateDialogClose(done) {
      console.log("addEditTemplateDialogClose::::");
      this.resetTemplateForm();
      done();
    },

    fileUploadSuccess(response, file, fileList) {
      console.log("fileUploadSuccess:::file", file);
      console.log("fileUploadSuccess:::fileList", fileList);
      if (response.code === 200) {
        this.templateForm.path = response.data.absolutePath;
      }
    },

    fileUploadError(err, file, fileList) {
      console.log("fileUploadError:::", err, file, fileList);
      this.$message.error("文件上传失败！");
    },

    fileUploadExceed(files, fileList) {
      console.log("fileUploadExceed:::", files, fileList);
      this.$message.error("模板文件只能上传一个！");
    },
  },
};
</script>

<style scoped>
.template-upload-container {
  width: 100%;
  text-align: center;
}
</style>